import { useRef } from 'react';

import { useAntdTable } from 'ahooks';
import { Button, DatePicker, Image, Popconfirm, Select, Table, Tag } from 'antd';
import { Dayjs } from 'dayjs';

import Filter from '@/components/filter';
import SearchInput from '@/components/search-input';
import Text from '@/components/text';

import { store } from '@/store';

import { usePermission } from '@/auth';
import { TimeSort } from '@/enum';
import { AppStatusObj } from '@/enum/app';
import { NoticeStatusObj } from '@/enum/notice';
import {
  sysApplicationDelete,
  sysApplicationVoPage
} from '@/services/base/quanxianmokuaiyingyongbiaojiekou';
import { parseSrc } from '@/utils';

import AppSwitch from './appSwitch';
import Edit, { EditRef } from './edit';

/** 该模块增删改查对象 */
export type BizObject = BASE.SysApplicationVO;

const Page: React.FC = () => {
  const permission = usePermission();
  const edit = useRef<EditRef>(null);
  const [filter] = Filter.useForm();
  const table = useAntdTable(
    async ({ current, pageSize }, { id, createTime, ...formData }) => {
      const [beginTime, endTime] = ((createTime as [Dayjs?, Dayjs?]) || []).map((v) =>
        v?.format('YYYY-MM-DD HH:mm:ss')
      );

      const res = await sysApplicationVoPage({
        ...formData,
        ...id,
        beginTime,
        endTime,
        page: current,
        size: pageSize,
        timeSort: TimeSort.倒序
      });

      return {
        list: res.data?.records || [],
        total: res.data?.total || 0
      };
    },
    {
      form: filter
    }
  );

  const onSearch = () => {
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  return (
    <>
      {/* 筛选 */}
      <Filter
        onFinish={onSearch}
        form={filter}
        extra={
          <>
            {permission.check() && (
              <Button
                onClick={() => {
                  edit.current?.open({
                    type: 'add',
                    onSuccess: () => {
                      table.refresh();
                    }
                  });
                }}
                type="primary"
              >
                创建应用
              </Button>
            )}
          </>
        }
      >
        <Filter.Item name="id">
          <SearchInput
            style={{
              width: 120 * 3
            }}
            typeList={[
              { value: 'appName', children: '通知名称' },
              { value: 'id', children: '通知ID' }
            ]}
          />
        </Filter.Item>

        <Filter.Item name="status">
          <Select
            style={{
              width: 120
            }}
            allowClear
            placeholder="状态"
            options={Array.from(NoticeStatusObj).map(([key, value]) => ({
              value: key,
              label: value.text
            }))}
          />
        </Filter.Item>

        <Filter.Item name="createTime">
          <DatePicker.RangePicker showTime placeholder={['创建开始时间', '创建结束时间']} />
        </Filter.Item>

        <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item>
      </Filter>
      {/* end 筛选 */}

      {/* 表格 */}
      <Table<BizObject>
        size="small"
        columns={[
          {
            title: 'id',
            dataIndex: 'id'
          },
          {
            title: '应用图标',
            dataIndex: 'appIcon',
            render: (v) => {
              if (!v) {
                return emptyText;
              }

              return <Image height={100} width={100} src={parseSrc(v)} />;
            }
          },
          {
            title: '应用名称',
            dataIndex: 'appName'
          },
          {
            title: '回调地址',
            dataIndex: 'redirectUrl'
          },
          {
            title: 'code过期时间（秒）',
            dataIndex: 'codeExpired'
          },
          {
            title: '应用状态',
            dataIndex: 'status',
            render: (v) => {
              const obj = AppStatusObj.get(v);

              if (obj) {
                return <Tag color={obj.color}>{obj.text}</Tag>;
              }

              return emptyText;
            }
          },
          {
            title: '应用状态',
            dataIndex: 'status',
            render: (_, row) => {
              return (
                <AppSwitch
                  data={row}
                  onChange={() => {
                    table.refresh();
                  }}
                />
              );
            }
          },
          {
            title: '创建时间',
            dataIndex: 'createTime'
          },
          {
            title: '操作',
            fixed: 'right',
            align: 'center',
            render: (_, row) => {
              return (
                <Text.Space>
                  <Text onClick={() => {}}>详情</Text>

                  <Text
                    onClick={() => {
                      // auth.current?.open({
                      //   rowData: row,
                      //   onSuccess: () => {
                      //     table.current?.reload();
                      //   },
                      // });
                    }}
                  >
                    授权
                  </Text>

                  <Text
                    onClick={() => {
                      // code.current?.open({
                      //   rowData: row,
                      //   onChange: () => {
                      //     table.current?.reload();
                      //   },
                      // });
                    }}
                  >
                    应用凭证
                  </Text>

                  {permission.check() && (
                    <Text
                      onClick={() => {
                        edit.current?.open({
                          type: 'edit',
                          rowData: row,
                          onSuccess: () => {
                            table.refresh();
                          }
                        });
                      }}
                      type="primary"
                    >
                      编辑
                    </Text>
                  )}

                  {permission.check() && (
                    <Popconfirm
                      title={`确定删除该通知吗？`}
                      onConfirm={async () => {
                        const res = await sysApplicationDelete({
                          id: row.id as unknown as string
                        });

                        store.app?.message.success(res.message);
                        table.refresh();

                        return res.success;
                      }}
                    >
                      <Text type="danger">删除</Text>
                    </Popconfirm>
                  )}
                </Text.Space>
              );
            }
          }
        ]}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        {...table.tableProps}
        pagination={{
          ...table.tableProps.pagination,
          showTotal: (total) => `共 ${total} 条`,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100']
        }}
      />
      {/* end表格 */}

      <Edit ref={edit} />
    </>
  );
};

export default Page;
